package com.tianshi.pxx.interceptor;


import com.tianshi.pxx.pojo.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //响应中文乱码
        response.setContentType("text/html;charset=UTF-8");
        //从session中获取用户信息
        HttpSession session = request.getSession();
        //判断用户是否登录
        User user = (User) session.getAttribute("currentUser");
        //如果登录，放行
        if(user!= null){
            return true;
        }else{
            //怎么重定向到登录页面呢？

            //如果未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/pages/login.html");
//            response.getWriter().write("请先登录!");
//
            return false;
        }
    }

}
